const csv = require('csv-parser');
const { Parser } = require('json2csv');
const fs = require('fs');
const path = require('path');
const Goods = require('../models/Goods');
const InboundDocument = require('../models/InboundDocument');
const OutboundDocument = require('../models/OutboundDocument');

class DataController {
  // 导出货物数据为CSV
  static exportGoodsToCSV(req, res) {
    Goods.findAll((err, goods) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '导出货物数据失败',
          error: err.message
        });
      }
      
      try {
        const json2csvParser = new Parser();
        const csvData = json2csvParser.parse(goods);
        
        const filename = `goods_export_${new Date().toISOString().slice(0, 10)}.csv`;
        const filepath = path.join(__dirname, '../../exports', filename);
        
        // 确保导出目录存在
        const exportDir = path.join(__dirname, '../../exports');
        if (!fs.existsSync(exportDir)) {
          fs.mkdirSync(exportDir, { recursive: true });
        }
        
        fs.writeFileSync(filepath, csvData);
        
        res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
        res.setHeader('Content-Type', 'text/csv');
        res.send(csvData);
      } catch (error) {
        res.status(500).json({
          success: false,
          message: '生成CSV文件失败',
          error: error.message
        });
      }
    });
  }
  
  // 导入货物数据从CSV
  static importGoodsFromCSV(req, res) {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的CSV文件'
      });
    }
    
    const results = [];
    const filepath = req.file.path;
    
    fs.createReadStream(filepath)
      .pipe(csv())
      .on('data', (data) => results.push(data))
      .on('end', () => {
        // 处理导入的数据
        let successCount = 0;
        let errorCount = 0;
        const errors = [];
        
        results.forEach((row, index) => {
          const goods = new Goods(
            null,
            row.name,
            row.sku,
            parseInt(row.quantity) || 0,
            row.location || '',
            row.status || 'inStock',
            row.batch_number || '',
            row.expiry_date || null
          );
          
          goods.save((err, result) => {
            if (err) {
              errorCount++;
              errors.push(`第${index + 1}行: ${err.message}`);
            } else {
              successCount++;
            }
            
            // 检查是否处理完所有数据
            if (successCount + errorCount === results.length) {
              // 删除临时文件
              fs.unlinkSync(filepath);
              
              res.json({
                success: true,
                message: `导入完成。成功: ${successCount}, 失败: ${errorCount}`,
                errors: errors
              });
            }
          });
        });
      })
      .on('error', (error) => {
        // 删除临时文件
        if (fs.existsSync(filepath)) {
          fs.unlinkSync(filepath);
        }
        
        res.status(500).json({
          success: false,
          message: '读取CSV文件失败',
          error: error.message
        });
      });
  }
  
  // 导出入库单据数据为CSV
  static exportInboundToCSV(req, res) {
    InboundDocument.findAll((err, documents) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '导出入库单据数据失败',
          error: err.message
        });
      }
      
      try {
        const json2csvParser = new Parser();
        const csvData = json2csvParser.parse(documents);
        
        const filename = `inbound_export_${new Date().toISOString().slice(0, 10)}.csv`;
        
        res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
        res.setHeader('Content-Type', 'text/csv');
        res.send(csvData);
      } catch (error) {
        res.status(500).json({
          success: false,
          message: '生成CSV文件失败',
          error: error.message
        });
      }
    });
  }
  
  // 导出出库单据数据为CSV
  static exportOutboundToCSV(req, res) {
    OutboundDocument.findAll((err, documents) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '导出出库单据数据失败',
          error: err.message
        });
      }
      
      try {
        const json2csvParser = new Parser();
        const csvData = json2csvParser.parse(documents);
        
        const filename = `outbound_export_${new Date().toISOString().slice(0, 10)}.csv`;
        
        res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
        res.setHeader('Content-Type', 'text/csv');
        res.send(csvData);
      } catch (error) {
        res.status(500).json({
          success: false,
          message: '生成CSV文件失败',
          error: error.message
        });
      }
    });
  }
}

module.exports = DataController;